package com.duobaoyu.dby.supply.biz.util;

import com.duobaoyu.dby.channel.common.util.EnvironmentUtils;
import com.duobaoyu.dby.common.core.util.DateUtils;
import com.duobaoyu.dby.supply.core.dinger.util.DingDingUtils;
import com.duobaoyu.dby.supply.db.entity.message.ChannelMessage;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 钉钉发送
 *
 * @author fengshaoyu
 * @version 1.0.0
 * @date 2023/9/27 17:51
 */
@Slf4j
@UtilityClass
public class DingDingExtUtils extends DingDingUtils {

	/**
	 * 渠道消息重试处理异常发送钉钉消息
	 * @param channelMessage
	 */
	public static void sendChannelMessageRetry(ChannelMessage channelMessage) {
		String active = EnvironmentUtils.environment();
		String msg = "\n> - 当前环境: active \n> - 告警时间: " + LocalDateTime.now().format(DateUtils.DEFAULT_DATE_TIME_FORMATTER) +
				"\n> - 渠道消息ID: channelMessageId\n> - 渠道消息Class:\n> channelMessageClass";
		msg = msg.replace("channelMessageId", channelMessage.getId())
				.replace("channelMessageClass", channelMessage.getClass().getName())
				.replace("active",active);
		DingDingUtils.sendMarkdownMsg(msg,"渠道消息处理异常");
	}

	/**
	 * 消息类型
	 *
	 * @param message 消息类型
	 * @param obj     消息对象
	 */
	public static void sendMessage(String message, Object obj) {
		Map<String, Object> objectToMap = getObjectToMap(obj);
		if (null != objectToMap) {
			for (Map.Entry<String, Object> stringObjectEntry : objectToMap.entrySet()) {
				String key = stringObjectEntry.getKey();
				message = message.replace(key, String.valueOf(stringObjectEntry.getValue()));
			}
			sendMarkdownMsg(message);
		}
	}

	/**
	 * 对象转换map
	 *
	 * @param obj obj
	 * @return Map<String, Object>
	 */
	private static Map<String, Object> getObjectToMap(Object obj) {
		try {
			Map<String, Object> map = new LinkedHashMap<>();
			Class<?> clazz = obj.getClass();
			for (Field field : clazz.getDeclaredFields()) {
				field.setAccessible(true);
				String fieldName = field.getName();
				Object value = field.get(obj);
				map.put(fieldName, value);
			}
			return map;
		} catch (IllegalAccessException e) {
			log.warn("message:{},data:{}","钉钉消息转换失败",e);
		}
		return null;
	}

	/**
	 * 默认数据填充
	 * @param message 钉钉消息
	 * @return String 钉钉消息
	 */
	private static String defaultMessage(String message){
		return null;
	}
}
